package main

import (
	"fmt"
	"sort"
	"strconv"
)

type person struct {
	Name string
	Age  int
}

type personSlice []person
type mapSlice []map[string]string

func (s personSlice) Len() int           { return len(s) }
func (s personSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age > s[j].Age }

func main() {
	// go sort包实例
	a := personSlice{
		{
			Name: "AAA",
			Age:  55,
		},
		{
			Name: "BBB",
			Age:  22,
		},
		{
			Name: "CCC",
			Age:  0,
		},
		{
			Name: "DDD",
			Age:  22,
		},
		{
			Name: "EEE",
			Age:  11,
		},
	}
	b := mapSlice{
		{
			"name": "aa",
			"age":  "1",
		},
		{
			"name": "c",
			"age":  "3",
		},
		{
			"name": "e",
			"age":  "5",
		},
		{
			"name": "d",
			"age":  "4",
		},
		{
			"name": "bb",
			"age":  "2",
		},
	}
	sort.Sort(a)
	fmt.Println("Sort:", a)

	// 自定义sort必须实现 len() swap() less() 方法， 源代码试用这这个方法拿到循环长度len()，和交换数据模式swap()，和比较less()
	sort.Stable(a)
	fmt.Println("Stable:", a)

	sort.Slice(a, func(i, j int) bool {
		return a[i].Age >= a[j].Age
	})
	fmt.Println(a)

	sort.Slice(b, func(i, j int) bool {
		m1, _ := strconv.Atoi(b[i]["age"])
		m2, _ := strconv.Atoi(b[j]["age"])
		return m1 > m2
	})
	fmt.Println(b)

}